from calc_manager.base.task import TaskFactory, DefaultRunnableTask, TaskInfo
from calc_manager.plugins.plugins_manager import PluginManager
from typing import Dict, Any
from calc_manager.operator import Operator
import logging

logger = logging.getLogger(__name__)


class DefaultTaskFactory(TaskFactory[DefaultRunnableTask]):
    def __init__(self, plugin_manager: PluginManager = None, plugins_argv: Dict[str, Any] = None):
        self.plugin_manager = plugin_manager
        self.plugins_argv = plugins_argv
        logger.debug(f"init default task factory by plugins_argv: {plugins_argv}")

    def create_task(self, info: TaskInfo) -> DefaultRunnableTask:
        df_task = DefaultRunnableTask(info, self.plugin_manager, self.plugins_argv)

        def pre_run(task: DefaultRunnableTask):
            _ctx = task.get_ctx()
            if self.plugin_manager:
                invoke_param = Operator.get_plugin_objects_from_argv(self.plugin_manager, self.plugins_argv)
                invoke_param = {k: v.get_plugin_ojbect() for k, v in invoke_param.items()}
                task.runnable.set_extra_param(**invoke_param)
                logger.debug(f"pre_run invoke_param: {invoke_param}")   
            else:
                logger.debug("plugin_manager is None, do not set extra param")
        df_task.add_pre_run_callable(pre_run)

        return df_task



